package com.example.mybrowser;

import androidx.appcompat.app.AppCompatActivity;
import androidx.percentlayout.widget.PercentRelativeLayout;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.wcl.notchfit.NotchFit;
import com.wcl.notchfit.args.NotchProperty;
import com.wcl.notchfit.args.NotchScreenType;
import com.wcl.notchfit.core.OnNotchCallBack;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    private PercentRelativeLayout rel_title,main_layout,rel_bg;
    private EditText et_wangzhi;
    private View fullScreenView = null;//播放视频的视图
    private WindowManager windowManager;
    private Button btn_sousuo,btn_reload;
    private TextView tv_process;
    private static final String TAG = "MainActivity";
    private ImageButton imgbtn_back,imgbtn_go,imgbtn_home,imgbtn_exit;
    private String webHomeUrl="https://www.baidu.com/";//主页地址
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void initwebview() {
        webView.loadUrl(webHomeUrl);
//        webView.loadUrl("https://haokan.baidu.com/v?vid=3762993832626028206&context=%7B%22nid%22%3A%22sv_3762993832626028206%22%7D&pd=feedtab_h5&pagepdSid=");
        WebSettings settings = webView.getSettings();
        settings.setTextZoom(100);//字体大小
        settings.setBlockNetworkImage(false);//解决图片不显示
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        settings.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        settings.setSupportZoom(true);//是否可以缩放，默认true
        settings.setBuiltInZoomControls(false);//是否显示缩放按钮，默认false
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式setJavaScriptEnabled
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        settings.setAppCacheEnabled(true);//是否使用缓存
        settings.setDomStorageEnabled(true);//DOM Storage

        // displayWebview.getSettings().setUserAgentString("User-Agent:Android");//设置用户标识
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//安卓5.0开始，webview中默认不允许混合模式。https当中不能加载http资源，需要设置开启
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);       //开启混合模式    解决网页中一些http的图片资源不能正常显示
        }

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if ( urlCanLoad(url.toLowerCase())) {  // 加载正常网页
                    view.loadUrl(url);
                }
                else {  // 打开第三方应用或者去应用商店下载apk
                    startThirdpartyApp(url);
                }
                return true;
            }

            //开始加载网页
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                et_wangzhi.setHint(view.getTitle());
            }

            //网页加载结束
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                et_wangzhi.setHint(view.getTitle());
            }

        });

        windowManager=getWindowManager();
        webView.setWebChromeClient(new WebChromeClient(){

            //网页加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                tv_process.setText("加载进度"+newProgress+"%");
                if (newProgress > 99) {
                    tv_process.setText("加载完成");
                }
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_APPLICATION);
                layoutParams.flags=FLAG_FULLSCREEN;
                /**
                 * FLAG_FULLSCREEN
                 *
                 * 当该窗口显示时, 隐藏所有屏幕装饰(如状态栏), 允许窗口使用整个屏幕
                 * 当带有该flag的窗口是顶层窗口时, 状态栏会被隐藏
                 * 全屏窗口会忽略SOFT_INPUT_ADJUST_RESIZE对于softInputMode的值
                 * 窗口会一直保持全屏, 且不能缩放
                 * 可以通过theme属性来控制, 如Theme_Black_NoTitleBar_Fullscreen等
                 */
                fullScreenView=new View(MainActivity.this);
                fullScreenView=view;
                windowManager.addView(fullScreenView,layoutParams);
//              setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏
                rel_bg.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onHideCustomView() {
                rel_bg.setVisibility(View.VISIBLE);
                windowManager.removeViewImmediate(fullScreenView);
                fullScreenView=null;
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }
        });
        webView.setDownloadListener(new WebViewDownloadListener());
    }


    private String str_search;//搜索栏存储的文字
    private void init() {
        webView=findViewById(R.id.main_webview);
        rel_title=findViewById(R.id.rel_title);
        main_layout=findViewById(R.id.main_layout);
        et_wangzhi=findViewById(R.id.et_wangzhi);
        initScreen(this);//屏幕适配
        initwebview();
        et_wangzhi.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    str_search = et_wangzhi.getHint().toString();
                    et_wangzhi.setHint("请输入网址或要搜索的内容");
                }else {
                    if (!str_search.isEmpty()){
                        et_wangzhi.setHint(str_search);
                    }
                }
            }
        });
        et_wangzhi.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if(i == 3){
                    search();
                }
                return false;
            }
        });
        btn_sousuo=findViewById(R.id.btn_sousuo);
        btn_sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search();
            }
        });
        rel_bg=findViewById(R.id.rel_bg);
        tv_process=findViewById(R.id.tv_process);
        imgbtn_back=findViewById(R.id.imgbtn_back);
        imgbtn_go=findViewById(R.id.imgbtn_go);
        imgbtn_home=findViewById(R.id.imgbtn_home);
        imgbtn_exit=findViewById(R.id.imgbtn_exit);
        imgbtn_back.setOnClickListener(new View.OnClickListener() {//返回监听
            @Override
            public void onClick(View view) {
                if (webView.canGoBack()) {
                    webView.goBack();
                }else {
                    Toast.makeText(MainActivity.this, "没有可以后退的页面了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        imgbtn_home.setOnClickListener(new View.OnClickListener() {//返回主页监听
            @Override
            public void onClick(View view) {
                webView.loadUrl(webHomeUrl);
            }
        });
        imgbtn_go.setOnClickListener(new View.OnClickListener() {//前进监听
            @Override
            public void onClick(View view) {
                if (webView.canGoForward()){
                    webView.goForward();
                }else {
                    Toast.makeText(MainActivity.this, "没有可以前进的页面了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        imgbtn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.exit(0);
            }
        });
        btn_reload=findViewById(R.id.btn_reload);
        btn_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView.reload();
            }
        });
    }





    private void search(){
        String s = et_wangzhi.getText().toString().trim();
        if (s.isEmpty()) {
            Toast.makeText(this, "请输入要搜索的内容或者要访问的网址", Toast.LENGTH_SHORT).show();
            return;
        }
        boolean httpUrl = isHttpUrl(s);
        if (httpUrl) {
            String substring = s.substring(0, 5);//该子字符串从指定的 beginIndex 处开始， endIndex:到指定的 endIndex-1处结束。
            if (("https").equalsIgnoreCase(substring) || ("http:").equalsIgnoreCase(substring)) {

            }else {
                s="https://"+s;
            }
            webView.loadUrl(s);
            et_wangzhi.setText("");
        }else {
            String url="https://www.baidu.com/s?wd="+s;
            webView.loadUrl(url);
            et_wangzhi.setText("");
        }
    }




    /**
     * 判断字符串是否为URL
     * @param urls 需要判断的String类型url
     * @return true:是URL；false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式
        Pattern pat = Pattern.compile(regex.trim());//对比
        Matcher mat = pat.matcher(urls.trim());
        isurl = mat.matches();//判断是否匹配
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
    private int notchHeight=0;//状态栏高度
    //屏幕适配
    private void initScreen(final Activity activity) {
        NotchFit.fit(activity, NotchScreenType.TRANSLUCENT, new OnNotchCallBack() {//沉浸式状态栏
            @Override
            public void onNotchReady(NotchProperty notchProperty) {//沉浸式状态栏
                if(notchProperty.isNotchEnable()){
                    //判断横竖屏
                    if (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
                        // 横屏
                        notchHeight = notchProperty.getNotchWidth();
                        Toast.makeText(activity, "横屏虚拟按键未适配，请使用全面屏手势", Toast.LENGTH_SHORT).show();
                    } else if (activity.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT) {
                        // 竖屏
                        notchHeight = notchProperty.getNotchHeight();

                        ViewGroup.LayoutParams layoutParams = main_layout.getLayoutParams();
                        layoutParams.height=getScreenHeight(activity)+notchHeight;
                        main_layout.setLayoutParams(layoutParams);
                    }
                    ViewGroup.LayoutParams layoutParams = rel_title.getLayoutParams();
                    layoutParams.height=notchHeight;
                    rel_title.setLayoutParams(layoutParams);
                }

                Window window = activity.getWindow();
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏颜色为黑色
//                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);//设置状态栏字体颜色为白色
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initScreen(this);
    }

    long time=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果按返回键，此时WebView网页可以后退
        if (keyCode== KeyEvent.KEYCODE_BACK&&webView.canGoBack()){
            webView.goBack();
            return true;
        }else {
            if (keyCode == event.KEYCODE_BACK) {
                if (System.currentTimeMillis() - time > 2000) {
                    Toast.makeText(getApplicationContext(), "再次点击退出程序!", Toast.LENGTH_SHORT).show();
                    time=System.currentTimeMillis();
                    return true;
                }else {
                    System.exit(0);
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 列举正常情况下能正常加载的网页url
     * @param url
     * @return
     */
    private boolean urlCanLoad(String url) {
        return url.startsWith("http://") || url.startsWith("https://") ||
                url.startsWith("ftp://") || url.startsWith("file://");
    }

    /**
     * 打开第三方app。如果没安装则跳转到应用市场
     * @param url
     */
    private void startThirdpartyApp(String url) {
        try {
            Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
//            测试下载百度app，第一次进入会直接跳转到运营商店的百度app下载页面，第二次返回app，点击立即下载，会打开别的app来下载。（跳转到别人的浏览器来下载)
//            测试通过点击scheme来打开怪兽bobo软件
        }
        catch (Exception e) {
//            Log.e(TAG, e.getMessage());
        }
    }

    private class WebViewDownloadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            downloadByBrowser(url);
        }
    }
    /**
     * 通过浏览器下载
     * @param url
     */
    private void downloadByBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }
/**
 * mainWebView.canGoBack()
 *
 * 检测浏览器是否可以后退
 *
 * 返回bool值
 *
 *
 *
 * mainWebView.goBack()
 *
 * 浏览器后退
 *
 *
 *
 * mainWebView.canGoForwad()
 *
 * 检测浏览器是否可以前进
 *
 * 返回bool值
 *
 *
 *
 * mainWebView.goForward()
 *
 * 浏览器前进
 *
 *
 *
 * mainWebView.clearCache(true)
 *
 * 清除浏览器缓存
 *
 *
 *
 * mainWebView.clearFormData()
 *
 * 清除浏览器表单数据
 *
 *
 *
 * mainWebView.getUrl()
 *
 * 获取浏览器网址
 *
 * 返回string值
 *
 *
 *
 * mainWebView.getTitle()
 *
 * 获取浏览器网页标题
 *
 * 返回string值
 * `
 */
}
